package com.sw.study.presisence.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.sw.study.presisence.io.Resources;
import com.sw.study.presisence.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created by sw on 2020/3/25.
 * xml 文件解析
 */
public class XMLConfigBuider {
    private Configuration configuration;

    public XMLConfigBuider() {
        this.configuration=new Configuration();
    }

    /**
     * 解析xml配置文件 封装为Configuration配置信息
     * @param inputStream  配置文件流
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document= new SAXReader().read(inputStream);
        Element rootElement=document.getRootElement();
        List<Element> elements= rootElement.selectNodes("//property");
        Properties properties=new Properties();
        String name=null;
        String value=null;
        for (Element e: elements){
            name=e.attributeValue("name");
            value=e.attributeValue("value");
            if(null==name){
                throw  new DocumentException("SqlMapConfig datasource name is null");

            }
            if(null==value){
                throw  new DocumentException("SqlMapConfig datasource value is null");
            }
            properties.setProperty(name,value);
        }
        if(properties.isEmpty()){
            throw  new DocumentException("SqlMapConfig.xml parse fail");
        }
        /**
         * db信息
         */
        ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("userName"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);
        /**
         * sqlMapperxml解析
         */
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        String mapperPath="";
        for(Element e:mapperList){
            mapperPath=e.attributeValue("resource");
            InputStream mapperStream= Resources.getResourcesAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder=new XMLMapperBuilder(configuration);
            xmlMapperBuilder.pareMapperXml(mapperStream);
        }
        return configuration;
    }
}